package com.baijing.springbootwebsocket.web;

import com.baijing.springbootwebsocket.domain.BaijingMessage;
import com.baijing.springbootwebsocket.domain.BaijingResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;


@Controller
public class WsController {

    /**
     * 广播
     */
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/welcome")
    @SendTo("/topic/getResponse")
    public BaijingResponse say(BaijingMessage message) throws Exception {
        Thread.sleep(3000);
        return new BaijingResponse("Welcome, " + message.getName() + " !");
    }

    /**
     * 点对点 对话框 硬编码
     *
     * @param principal
     * @param msg
     */
    @MessageMapping("/chat")
    public void handleChat(Principal principal, String msg) {
        if (principal.getName().equals("bj")) {
            simpMessagingTemplate.convertAndSendToUser("xa", "/queue/notifications", principal.getName() + "-send:" + msg);
        } else {
            simpMessagingTemplate.convertAndSendToUser("bj", "/queue/notifications", principal.getName() + "-send" + msg);
        }
    }
}
